<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/7/3 16:06
 */

namespace App\Utils;


use EasyWeChat\MiniApp\Application;
use Hyperf\Context\ApplicationContext;
use Psr\SimpleCache\CacheInterface;
use function Hyperf\Config\config;
use function Hyperf\Support\make;

class HelperUtils
{

    /**
     * 小程序缓存使用redis 驱动
     * @param array $config
     * @param string $namespace
     * @return Application
     */
    public static function miniProgram(array $config = [])
    {
        if(empty($config)) {
            $config = config('wechat.mini_program');
        }

        $application = make(Application::class,[$config]);

//        // region request替换请求
//        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
//        $application->setRequest($request);


        // region 替换缓存redis
        $cache = ApplicationContext::getContainer()->get(CacheInterface::class);
        $application->setCache($cache);

        return $application;

    }


    /**
     * 判断字符串是否为JSON
     * @param string $string
     * @return bool
     */
    public static function isJson($string) {
        // 尝试解码JSON字符串
        $decoded = json_decode($string);

        // 检查解码后的结果是否为null，并且检查错误
        return ($decoded !== null && json_last_error() === JSON_ERROR_NONE);
    }


    //判断手机号
    public static function isMobile($mobile)
    {
        if (preg_match("/^1\d{10}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 生成随机字符串
     * @return string
     * @throws \Random\RandomException
     */
    public static function generateMemberCardEnhanced() {

        $datePart = date('ymd');
        $microtime = explode(' ', microtime());
        $timePart = substr($microtime[0], 2, 4);
        $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $length = 4;
        $randomPart = '';
        for ($i = 0; $i < $length; $i++) {
            $randomPart .= $chars[random_int(0, strlen($chars) - 1)];
        }
        return $datePart . $timePart . $randomPart;
    }
}